package algorithm.leetcode.codeutils;

import java.util.List;

/**
 * @program: util
 * @description: java链表
 * @author: zhouliangliang
 * @create: 2021-04-12 17:18
 **/
public class ListNode<T> {

    private T value;
    private ListNode<T> next;

    public ListNode(T v, ListNode<T> ne) {
        this.value = v;
        this.next = ne;
    }

    public ListNode() {}

//    public ListNode() {
//        this.value = null;
//        this.next = null;
//    }
//
//    public void add(T added) {
//        this.value
//        this.next = added;
//    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public ListNode<T> getNext() {
        return next;
    }

    public void setNext(ListNode<T> next) {
        this.next = next;
    }

    public String toString() {
        ListNode<T> node = this;
        StringBuilder builder = new StringBuilder();
        while (node != null) {
            builder.append(node.value).append(" ");
            node = node.next;
        }
        System.out.println(builder.toString());
        return builder.toString();
    }

    public static <T> ListNode<T> build(List<T> source) {
        ListNode<T> head = null;
        ListNode<T> list = new ListNode<>();
        head = list;

        for(int i=0; i<source.size(); i++) {
            T t = source.get(i);
            list.setValue(t);
            if(i + 1 >= source.size()) {
                list.setNext(null);
            } else {
                list.setNext(new ListNode<>());
                list = list.next;
            }
        }
        return head;
    }
}
